package com.wzbc.video.controller;

import com.wzbc.video.api.CommonResult;
import com.wzbc.video.dto.LoginDto;
import com.wzbc.video.entity.User;
import com.wzbc.video.req.IdReq;
import com.wzbc.video.req.UserSearchReq;
import com.wzbc.video.req.UserReq;
import com.wzbc.video.service.UserService;
import com.wzbc.video.utils.TokenUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/user")
@Api(tags = "用户管理")
public class UserController {

    @Autowired
    public UserService userService;

    @Autowired
    public TokenUtil tokenUtil;

    @PostMapping("/login")
    @ApiOperation("登录")
    public CommonResult login(@RequestBody LoginDto loginDto) {

        if (userService.validateUsername(loginDto.username) == 0) {
            return CommonResult.failed("username");
        }
        Long uid = userService.validateLogin(loginDto.username, loginDto.password);
        if (uid.equals(0L)) {
            return CommonResult.failed("password");
        }
        return CommonResult.success(tokenUtil.createToken(String.valueOf(uid)));
    }

    @PostMapping("/logout")
    public CommonResult logout(HttpServletRequest req) {
        if (!tokenUtil.removeToken(req.getHeader("X-Token"))) {
            return CommonResult.failed("bad");
        }
        return CommonResult.success("success");
    }

    @PostMapping("/info")
    public CommonResult getinfo(HttpServletRequest req) {
        return CommonResult.success(userService.getById(Long.parseLong(tokenUtil.getToken(req.getHeader("X-Token")))));
    }

    @PostMapping("/getUsers")
    public CommonResult getUsers(@RequestBody UserSearchReq req) {
        return CommonResult.success(userService.myList(req));
    }

    @PostMapping("/edit")
    public CommonResult editUser(@RequestBody UserReq req) {
        User user = new User();
        BeanUtils.copyProperties(req,user);
        return CommonResult.success(userService.updateById(user));
    }
    @PostMapping("/insert")
    public CommonResult importUser(@RequestBody User user) {
        return CommonResult.success(userService.insert(user));
    }
    @PostMapping("/delete")
    public CommonResult deleteUser(@RequestBody IdReq req) {
        return CommonResult.success(userService.deleteById(req.getId()));
    }
}